Ext.define('Jason.view.protal.authentication.AuthenticationController', {
    extend: 'Ext.app.ViewController',
    alias: 'controller.authentication',
    init: function () {
        session.set('userKeyPlateLogin', true);
        session.set('SINGLEONLINE', true);
        session.set('enableIM', true);
    },
    onAccountLogin: function (button, e) {
        button.up('window').close();
    },
    onLoginButton: function (button, e, eOpts) {
        var self = this,
            authdialog = button.up('form');//authdialog
        if (!authdialog.getForm().isValid()) {
            return;
        }
        EUtil.RS({
            url: reqUrl.sys.login,
            params: Ext.apply(authdialog.getForm().getValues(),{
        		password:CUtil.encryptByAes(authdialog.getForm().getValues().password)
        	}),
            message: I18N.LoginSubmitWaitMsg,
            msg: true,
            callback: function (result) {
                if (result.success) {
                    local.set('P', CUtil.encryptByAes(authdialog.down('textfield[name=password]').getValue()));
                    session.set('loginState', true);
                    session.set('token', result.data.token);
                    session.set('refreshToken', result.data.refreshToken);
                    session.set('username', result.data.username);
                    session.set('realname', result.data.realname);
                    session.set('dept', result.data.dept);
                    session.set('post', result.data.post);
                    session.set('theme', result.data.theme);
                    session.set('permissions', result.data.permissions);
                    session.set('access_token', result.data.token);
                    session.set('firstLoad',true);
                    Ext.util.History.setHash("dashboard");
                    // window.location.reload();
                    var topMenuConst = self.getView().up('mainView').down('customMenu');
                    topMenuConst.fireEvent('render', topMenuConst);
                    try{
                        //refresh
                        var mainView = self.getView().up('mainView');
                        mainView.getViewModel().initUserLocalSetter();
                        mainView.getViewModel().set('loginedProfile','<div class="back-sky-layout-header-nav-user-info">' +
                            '   <div class="back-sky-layout-header-nav-user-name">' +
                            (session.get('realname') || '暂未登录') +
                            '   </div> ' +
                            '   <div class="back-sky-layout-header-nav-user-category">' +
                            (session.get('dept') || '暂未登录') +
                            '   </div>' +
                            '</div>');
                        //手动触发一次页面绘制
                        mainView.getController()._onInitPageStyle();
                    }catch(e){};
                } else {
                    authdialog.down('fieldVerify').onClearValue();
                    authdialog.down('fieldVerify').onRefreshImg();
                    EUtil.showError(Ext.String.format(I18N.FailedOtherCode, result.code, result.msg));
                }
            }
        });
    },

    onLoginAsButton: function (button, e, eOpts) {
        this.redirectTo("protal.authentication.Login");
    },

    onNewAccount: function (button, e, eOpts) {
        //        this.redirectTo("authregister",true);
        Ext.create('Jason.view.protal.authentication.Register', {}).show();
    },

    onSignupClick: function (button, e, eOpts) {
        var me = this;
        var regWin = button.up('authregister'),
            authdialog = regWin.down('form');//authdialog
        if (!authdialog.getForm().isValid()) {
            return;
        }
        EUtil.RS({
            url: reqUrl.sys.registerAccount,
            params: authdialog.getValues(),
            msg: true,
            callback: function (resp) {
                if (resp.success) {
                    regWin.close();
                    EUtil.showSuccess(resp.data || '账号注册成功！！！');
                } else {
                    EUtil.showError(Ext.String.format(I18N.FailedOtherCode, result.code, result.msg));
                }
            }
        });
    },

    onResetClick: function (button, e, eOpts) {
        this.redirectTo("protal.dashboard");
    },
    onPersistChange: function (this_, newValue, oldValue, eOpts) {
        var self = this,
            check = this_.getValue(),
            authdialog = this_.up('form');
        if (check) {
            local.set('usid', authdialog.down('textfield[name=loginName]').getValue());
            local.set('pwd', authdialog.down('textfield[name=password]').getValue());
        } else {
            local.set('usid', '');
            local.set('pwd', '');
        }
    },
    /**
     * 用户中心使用，退出系统
     */
    onSignOut: function (btn, e, eOpts) {
        EUtil.showMsg({
            option: 3,
            title: '退出系统',
            message: '您确认要退出系统？',
            callback: function (btn) {
                if (btn === 'ok') {
                    EUtil.RS({
                        url: reqUrl.sys.logout,
                        callback: function (result) {
                            if (result.success) {
                                session.clean();
//                                Ext.Array.each(Ext.ComponentQuery.query('mainView'), function (obj) {
//                                    obj.destroy();
//                                });
//                                Ext.create('Jason.view.Main');
								this.redirectTo("protal.authentication.Login");                                
                            } else {
                                EUtil.toast(result.msg_info, 2);
                            }
                        }
                    });
                }
            }
        });
    },
    /**
     * 用户中心使用，修改密码
     */
    onChenagePasscode: function (btn, e, eOpts) {
        Ext.create('Ext.window.Window', {
            title: I18N.PasswordResetTitle,
            modal: true,
            iconCls: 'fa fa-edit',
            width: 400,
            resizable: false,
            closable: true,
            layout: 'fit',
            items: [{
                xtype: 'authdialog',
                itemId: 'changePasscodeForm',
                autoComplete: false,
                bodyPadding: '20 20',
                layout: {
                    type: 'vbox',
                    align: 'stretch'
                },
                defaults: {
                    margin: '10 0'
                },
                items: [{
                    xtype: 'textfield',
                    cls: 'auth-textbox',
                    height: 55,
                    inputType: 'password',
                    name: 'sourcePwd',
                    hideLabel: true,
                    allowBlank: false,
                    emptyText: '请输入原登录密码',
                    triggers: {
                        glyphed: {
                            cls: 'trigger-glyph-noop auth-password-trigger'
                        }
                    }
                }, {
                    xtype: 'textfield',
                    cls: 'auth-textbox',
                    height: 55,
                    inputType: 'password',
                    name: 'newPassword',
                    hideLabel: true,
                    allowBlank: false,
                    emptyText: '请输入新密码',
                    triggers: {
                        glyphed: {
                            cls: 'trigger-glyph-noop auth-password-trigger'
                        }
                    }
                }, {
                    xtype: 'textfield',
                    cls: 'auth-textbox',
                    height: 55,
                    inputType: 'password',
                    name: 'confimPwd',
                    hideLabel: true,
                    allowBlank: false,
                    emptyText: '请再次输入新密码',
                    triggers: {
                        glyphed: {
                            cls: 'trigger-glyph-noop auth-password-trigger'
                        }
                    }
                }, {
                    xtype: 'button',
                    reference: 'resetPassword',
                    scale: 'large',
                    ui: 'soft-blue',
                    formBind: true,
                    text: I18N.Selected,
                    listeners: {
                        click: function (btn) {
                            var form = btn.up('#changePasscodeForm');
                            EUtil.RS({
                                url: reqUrl.sys.changePassCode,
                                params: form.getValues(),
                                callback: function (result) {
                                    if (result.success) {
                                        EUtil.showMsg({
                                            message: I18N.PasswordResetSuccess, option: 0,
                                            callback: function (btn) {
                                                session.clean();
                                                Ext.Array.each(Ext.ComponentQuery.query('mainView'), function (obj) {
                                                    obj.destroy();
                                                });
                                                Ext.create('Jason.view.Main');
                                            }
                                        })
                                    } else {
                                        EUtil.toast(result.msg_info, 2);
                                    }
                                }
                            });
                        }
                    }
                }]
            }]
        }).show();
    },
    onUnLockPage: function (btn) {
        var pwdIn = btn.up().down('#password'),
            view = Ext.ComponentQuery.query('lockscreen');
        if (CUtil.encryptByAes(pwdIn.getValue()) === local.get('P')) {
            for (var key in view) {
                view[key].destroy();
            }
        } else {
            EUtil.toastWarn('登录密码不正确，轻轻重新输入');
            pwdIn.setValue('');
        }
    }
});
